package cn.open.feishu.alert.support.Handler;

import cn.open.feishu.alert.common.annotation.AlertHandler;
import cn.open.feishu.alert.common.enums.AlertModeEnum;
import cn.open.feishu.alert.common.enums.AlertTypeEnum;
import cn.open.feishu.alert.common.model.CardAlertRequest;
import cn.open.feishu.alert.common.model.CardAlertResponse;
import cn.open.feishu.alert.common.utils.HttpUtil;
import cn.open.feishu.alert.config.ButtonProperties;
import cn.open.feishu.alert.config.FeiShuProperties;
import cn.open.feishu.alert.support.FeishuAlertClient;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;

import java.io.IOException;

import static cn.open.feishu.alert.common.FeishuConstant.SUCCESS_CODE;

/**
 * @Description 飞书消息自定义机器人下发:群聊@服务负责人
 * @Author fandy.lin
 * @Date 2021/11/11 2:10 下午
 **/
@Slf4j
@AlertHandler(AlertModeEnum.AT_CHARGE_PERSON)
public class AtFeishuAlertHandler extends BaseFeishuAlertHandler implements FeishuAlertHandler {
    public AtFeishuAlertHandler(Environment env, FeiShuProperties feiShuProperties, ButtonProperties buttonProperties, FeishuAlertClient feishuAlertClient) {
        super(env, feiShuProperties, buttonProperties, feishuAlertClient);
    }

    @Override
    public void send(String robotName, String alertText, AlertTypeEnum alertType) {
        String realSendUrl = null;
        CardAlertRequest alertReq = null;
        try {
            //构建卡片请求
            alertReq = buildCardRequest(alertText, alertType, true);
            //构建自定义机器人url
            realSendUrl = getCustomRobotUrl(robotName);
            //发送告警消息
            CardAlertResponse alertResp = HttpUtil.execute(realSendUrl, null, alertReq, CardAlertResponse.class);
            if (SUCCESS_CODE != alertResp.getStatusCode()) {
                log.warn("feishu alert:send at alert fail,ret code={},msg={}", alertResp.getStatusCode(), alertResp.getStatusMessage());
            }
        } catch (IOException e) {
            log.error("feishu alert:send at alert error,send url={},req={}", realSendUrl, JSON.toJSONString(alertReq), e);
        }
    }
}
